package jsu.ljy.api.controller;

import jsu.ljy.api.common.ApiResponse;
import jsu.ljy.api.entity.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {
    
    // 模拟数据库存储
    private static final Map<Long, User> userMap = new HashMap<>();
    private static long idCounter = 1;

    @GetMapping
    public ApiResponse<List<User>> getAllUsers() {
        return ApiResponse.success(new ArrayList<>(userMap.values()));
    }

    @GetMapping("/{id}")
    public ApiResponse<User> getUserById(@PathVariable Long id) {
        User user = userMap.get(id);
        if (user == null) {
            return ApiResponse.error(404, "User not found");
        }
        return ApiResponse.success(user);
    }

    @PostMapping
    public ApiResponse<User> createUser(@RequestBody User user) {
        user.setId(idCounter++);
        userMap.put(user.getId(), user);
        return ApiResponse.success(user);
    }

    @PutMapping("/{id}")
    public ApiResponse<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        if (!userMap.containsKey(id)) {
            return ApiResponse.error(404, "User not found");
        }
        user.setId(id);
        userMap.put(id, user);
        return ApiResponse.success(user);
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteUser(@PathVariable Long id) {
        if (!userMap.containsKey(id)) {
            return ApiResponse.error(404, "User not found");
        }
        userMap.remove(id);
        return ApiResponse.success(null);
    }
} 